#include "head.h"

List *createList()
{
    List* newList = (List*)malloc(sizeof(List));
    newList->front = NULL;
    newList->rear = NULL;
    newList->size = 0;
    return newList;
}

Stack *createStack(){
    List* newList = (List*)malloc(sizeof(List));
    newList->front = NULL;
    newList->rear = NULL;
    newList->size = 0;
    return newList;
}

char* stackPeek(Stack* stack){
    return stack->front->data;
}

int stackPush(Stack* stack, char* data){
    rearInsert(stack, data);
    return 0;
}

char* stackPop(Stack* stack){
    char* ch = stack->front->data;
    node_t* pNode = stack->front;
    stack->front = stack->front->next;
    free(pNode);
    stack->size--;
    return ch;
}

int rearInsert(List *list, char *data)
{
    node_t *newNode = (node_t *)malloc(sizeof(node_t));
    newNode->data = data;
    newNode->next = NULL;
    if (list->size == 0)
    {
        list->front = newNode;
        list->rear = newNode;
    }
    else
    {
        list->rear->next = newNode;
        list->rear = newNode;
    }
    list->size++;
    return 0;
}

int frontInsert(List *list, char *data)
{
    node_t *newNode = (node_t *)malloc(sizeof(node_t));
    newNode->data = data;
    newNode->next = NULL;
    if (list->size == 0)
    {
        list->front = newNode;
        list->rear = newNode;
    }
    else
    {
        newNode->next = list->front;
        list->front = newNode;
    }
    list->size++;
    return 0;
}

int deleteList(List *list, char *data)
{
    node_t *pNode = list->front;
    node_t *pNext = pNode->next;
    ERROR_CHECK(pNode == NULL, 1, "empty list.\n");
    if (list->size == 1)
    {
        if(strcmp(data, pNode->data) == 0){
            list->front = NULL;
            list->rear = NULL;
            free(pNode);
        }
    }else
    {
        while (pNext->next != NULL)
        {
            if (strcmp(data, pNext->data) == 0)
            {
                pNode->next = pNext->next;
                pNext->next = NULL;
                free(pNext);
            }
            pNode = pNext;
            pNext = pNext->next;
        }
    }
    list->size--;
    return 0;
}

List* searchList(List* list, char *data){
    node_t *pNode = list->front;
    node_t *pNext = pNode->next;
    ERROR_CHECK(pNode == NULL, 1, "empty list.\n");
    if (list->size == 1)
    {
        if(strcmp(data, pNode->data) == 0){
            return pNode;
        }
    }else
    {
        while (pNext->next != NULL)
        {
            if (strcmp(data, pNext->data) == 0) return pNext;
            pNode = pNext;
            pNext = pNext->next;
        }
    }
    return NULL;
}

int destoryList(List *list){
    if(list->size == 0){
        free(list);
    }else{
        node_t *pNode = list->front;
        while(pNode != NULL){
            list->front = list->front->next;
            free(pNode);
            pNode = list->front;
        }
        free(list);
    }
    return 0;
}

